package com.ysdz.tibetan.tibetanmini.product.service.impl;

import com.ysdz.tibetan.tibetanmini.product.beans.Category;
import com.ysdz.tibetan.tibetanmini.utils.RedisUtils;
import com.ysdz.tibetan.tibetanminicommons.common.ReturnMsg;
import com.ysdz.tibetan.tibetanmini.product.beans.CategoryDetail;
import com.ysdz.tibetan.tibetanmini.product.dao.CategoryDetailMapper;
import com.ysdz.tibetan.tibetanmini.product.service.CategoryDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service
public class CategoryDetailServiceImpl implements CategoryDetailService {
    @Autowired
    private CategoryDetailMapper categoryDetailMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public ReturnMsg catagoryDetailList() {
        String key = "category_detail_all";
        ValueOperations<String, List<CategoryDetail>> operations = redisTemplate.opsForValue();
        boolean hasKey = redisTemplate.hasKey(key);
        if(hasKey){
            List<CategoryDetail> categories = operations.get(key);
            return new ReturnMsg(ReturnMsg.SUCCESS_CODE, "成功！", categories);
        }else{
            List<CategoryDetail> categories = categoryDetailMapper.selectAll();
            // 写入缓存
            operations.set(key, categories);
            return new ReturnMsg(ReturnMsg.SUCCESS_CODE, "成功！", categories);
        }
    }

    @Override
    public ReturnMsg getDetailByParentId(Integer id) {
        String key = "category_detail_" + id;
        ValueOperations<String, List<CategoryDetail>> operations = redisTemplate.opsForValue();
        boolean hasKey = redisTemplate.hasKey(key);
        if(hasKey){
            List<CategoryDetail> categories = operations.get(key);
            return new ReturnMsg(ReturnMsg.SUCCESS_CODE, "成功！", categories);
        }else{
            Example example = new Example(CategoryDetail.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("parent_id", id);
            List<CategoryDetail> categoryList = categoryDetailMapper.selectByExample(example);
            // 写入缓存
            operations.set(key, categoryList);
            return new ReturnMsg(ReturnMsg.SUCCESS_CODE, "成功！", categoryList);
        }
    }
}
